import React, { PureComponent } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import {
  Menu,
  Dropdown,
  PageHeader,
  Row,
  Col,
  Card,
  Icon,
  Button,
  Typography,
  Avatar,
  Skeleton,
  Drawer,
  Statistic,
  Tooltip,
  Tag,
} from 'antd'
import { Color } from 'utils'
import { Page, ScrollBar } from 'components'
import {
  NumberCard,
  Quote,
  Sales,
  Weather,
  RecentSales,
  Comments,
  Completed,
  Browser,
  Cpu,
  User,
  GCalendarComponent,
  RadaComponent,
  Radanotrans,
  DeviceInfoComponent,
} from './components'
import styles from './index.less'
import CountUp from 'react-countup'
import { withI18n, Trans } from '@lingui/react'
import AutoResponsive from 'autoresponsive-react'

const { Title, Text } = Typography
const { Meta } = Card
const bodyStyle = {
  bodyStyle: {
    height: 432,
    background: '#fff',
  },
}
const max1 = { max: 0 }
const max2 = { max: 0 }

Array.prototype.remove = function(val) {
  var index = this.indexOf(val)
  if (index > -1) {
    this.splice(index, 1)
  }
}
@withI18n()
@connect(({ app, dashboard, loading }) => ({
  avatar: app.user.avatar,
  app,
  dashboard,
  loading,
}))
class Dashboard extends PureComponent {
  state = {
    drawablevisible: false,
    containerWidth: undefined,
    collapsed: false,
  }

  componentDidMount() {
    const { dispatch } = this.props
    let container = ReactDOM.findDOMNode(this.refs.container)
    this.setState({
      containerWidth: container
        ? container.clientWidth
        : document.body.clientWidth,
    })
    window.addEventListener(
      'resize',
      () => {
        let container = ReactDOM.findDOMNode(this.refs.container)
        this.setState({
          containerWidth: container
            ? container.clientWidth
            : document.body.clientWidth,
        })
      },
      false
    )
  }

  // componentWillUnmount() {
  //   window.removeEventListener()
  // }

  componentWillReceiveProps(nextprops) {
    const { collapsed } = nextprops
    if (collapsed != this.state.collapsed) {
      setTimeout(() => {
        let container = ReactDOM.findDOMNode(this.refs.container)
        this.setState({
          containerWidth: container
            ? container.clientWidth
            : document.body.clientWidth,
        })
      }, 300)
    }
  }

  render() {
    const { avatar, dashboard, dispatch, app, i18n, loading } = this.props
    const { containerWidth } = this.state
    const { data } = dashboard
    const { isMobile } = app
    if (!data) return <Skeleton />
    const { userdata } = data
    const dashboardloading = loading.effects[`dashboard/query`]
    // console.log("containerWidth:" + containerWidth)
    const ondeletecard = cardtype => {
      dispatch({
        type: 'dashboard/operatedashboard',
        payload: { cardname: cardtype, status: false },
      }).then(() => {
        dispatch({ type: 'dashboard/query' })
      })
    }
    const onaddcard = cardtype => {
      dispatch({
        type: 'dashboard/operatedashboard',
        payload: { cardname: cardtype, status: true },
      }).then(() => {
        dispatch({ type: 'dashboard/query' })
      })
    }
    const getuserday = () => {
      var stime = Date.parse(new Date(userdata.createdAt))
      var etime = Date.parse(new Date())
      var usedTime = etime - stime //两个时间戳相差的毫秒数
      var days = Math.floor(usedTime / (24 * 3600 * 1000))
      return days
    }
    const cardtitles = (title, cardtype, tstyle) => ({
      title: (
        <span>
          {/* <Icon
            type="info-circle"
            style={{ display: 'inline-block', marginRight: '5px' }}
          /> */}
          <Title style={{ display: 'inline-block' }} level={4}>
            {title}
          </Title>
        </span>
      ),
      extra: (
        <Dropdown
          trigger="click"
          overlay={
            <Menu>
              <Menu.Item
                onClick={e => {
                  ondeletecard(cardtype)
                }}
              >
                <Trans>Delete</Trans>
              </Menu.Item>
            </Menu>
          }
        >
          <Icon
            type="more"
            style={{
              fontSize: '15px',
              background: '#eee',
              borderRadius: '2px',
              padding: '5px',
              cursor: 'pointer',
            }}
          />
        </Dropdown>
      ),
      style: {
        cursor: 'default',
        width: '100%',
        padding: '10px',
        // minHeight: isMobile ? '0px' : '200px',
        ...tstyle,
      },
    })

    const card = {
      Reports: item => {
        const width = containerWidth // containerWidth >= 500 ? (containerWidth) :
        const style = { width: width - 10, height: '370px' }
        return (
          <div key="Reports" className="item" href="#" style={style}>
            <Card
              hoverable
              size="small"
              key={'Apis'}
              {...cardtitles(
                <Trans>Number of Reporting in Project</Trans>,
                'Reports',
                style
              )}
            >
              {<Radanotrans datas={item} />}
            </Card>
          </div>
        )
      },
      EApis: item => {
        const width = containerWidth // containerWidth >= 500 ? (containerWidth) :
        const style = { width: width - 10, height: '370px' }
        return (
          // <Col xs={24} sm={24} md={24} lg={24} xl={24} xxl={12}>
          <div key="EApis" className="item" href="#" style={style}>
            <Card
              hoverable
              size="small"
              {...cardtitles(<Trans>Call API details</Trans>, 'EApis', style)}
            >
              {<RadaComponent datas={item} />}
            </Card>
          </div>
          // </Col>
        )
      },
      DailyApi: item => {
        const width =
          containerWidth >= 500 && data.keys.indexOf('DailyReport') != -1
            ? containerWidth / 2
            : containerWidth
        const style = { width: width - 10, height: '250px' }
        return (
          // <Col xs={24} sm={24} md={24} lg={24} xl={24} xxl={12}>
          <div key="DailyApi" className="item" href="#" style={style}>
            <Card
              hoverable
              size="small"
              key={'DailyApi'}
              {...cardtitles(
                <span>
                  <Trans>Number of API calls</Trans>:&nbsp;
                  <CountUp
                    start={0}
                    end={item.total}
                    duration={2}
                    useEasing
                    useGrouping
                    separator=","
                  />
                </span>,
                'DailyApi',
                style
              )}
            >
              <GCalendarComponent datas={item.datas} max={max1} />
            </Card>
          </div>
          // </Col>
        )
      },
      DailyReport: item => {
        const width =
          containerWidth >= 500 && data.keys.indexOf('DailyApi') != -1
            ? containerWidth / 2
            : containerWidth
        const style = { width: width - 10, height: '250px' }
        return (
          // <Col xs={24} sm={24} md={24} lg={24} xl={24} xxl={12}>
          <div key="DailyReport" className="item" href="#" style={style}>
            <Card
              hoverable
              size="small"
              key={'DailyReport'}
              {...cardtitles(
                <span>
                  <Trans>Number of data reporting</Trans>:&nbsp;
                  <CountUp
                    start={0}
                    end={item.total}
                    duration={2}
                    useEasing
                    useGrouping
                    separator=","
                  />
                </span>,
                'DailyReport',
                style
              )}
            >
              <GCalendarComponent datas={item.datas} max={max2} />
            </Card>
          </div>
          // </Col>
        )
      },
      DeviceInfo: item => {
        const width = containerWidth
        const style = { width: width - 10, height: '150px' }
        return (
          <div key="DeviceInfo" className="item" style={style}>
            <Card
              hoverable
              size="small"
              {...cardtitles(
                <Trans>Existing equipment</Trans>,
                'DeviceInfo',
                style
              )}
            >
              <DeviceInfoComponent item={item} isMobile={isMobile} />
            </Card>
          </div>
        )
      },
    }

    let cards = []
    let allcards = data.allkeys
    if (data && data.keys && data.keys.length > 0) {
      data.keys.forEach(item => {
        if (card[item] != undefined) {
          cards.push(card[item](data[item]))
          allcards.remove(item)
        }
      })
    }
    // console.log("allcards:" + allcards);
    // [<div className="item" style={{ width: "300px", height: "300px" }}></div>]
    // cards = cards.remove("fuck")
    const getAutoResponsiveProps = () => {
      return {
        itemMargin: 5,
        containerWidth: containerWidth || document.body.clientWidth,
        itemClassName: 'item',
        // gridWidth: 100,
        transitionDuration: '.1',
      }
    }
    const rolecard = {
      管理员: (
        <Tag color="gold">
          {' '}
          <Icon type="user" />
          管理员
        </Tag>
      ),
      普通用户: (
        <Tag color="blue">
          <Icon type="contacts" />
          普通用户
        </Tag>
      ),
    }
    return (
      <div>
        <PageHeader style={{ paddingBottom: '40px' }}>
          {dashboardloading || userdata == undefined ? (
            <Skeleton />
          ) : (
            <div
              style={{
                display: 'block',
                paddingLeft: isMobile ? '0px' : '30px',
                paddingRight: isMobile ? '0px' : '30px',
              }}
            >
              <Meta
                avatar={<Avatar size={64} src={avatar} />}
                title={
                  <span>
                    {userdata.username}&nbsp;&nbsp;
                    {rolecard[userdata.role]}
                  </span>
                }
                description={
                  <span style={{ fontSize: '15px' }}>
                    <Trans>This is the</Trans>&nbsp;
                    <CountUp
                      start={0}
                      end={getuserday()}
                      duration={3}
                      useEasing
                      useGrouping
                      separator=","
                    />
                    &nbsp;
                    <Trans>day you use the platform</Trans>
                  </span>
                } //{userdata.role}
                style={{ display: 'inline-block' }}
              />
              {/* <Statistic
                  style={{ display: 'inline-block', float: 'right' }}
                  title="Unmerged"
                  value={93}
                  suffix="/ 100"
                /> */}
              <div style={{ display: 'inline-block', float: 'right' }}>
                <Tooltip
                  placement="left"
                  title={i18n.t`Customize your home page`}
                >
                  <Button
                    block
                    size="default"
                    type="primary"
                    onClick={e => {
                      this.setState({ drawablevisible: true })
                    }}
                    style={{ backgroundColor: '#3E4C72', borderWidth: '0px' }}
                  >
                    <Icon type="plus" />
                    &nbsp;{<Trans>Add card</Trans>}
                  </Button>
                </Tooltip>
              </div>
            </div>
          )}
        </PageHeader>
        {/* <Row gutter={24} style={{ marginBottom: '10px', marginTop: '20px', marginRight: "20px" }}>
          <Col xs={12} sm={15} md={16} lg={18} xl={20} xxl={20} />
          <Col xs={12} sm={9} md={8} lg={6} xl={4} xxl={4}>

          </Col>
        </Row> */}
        <div
          style={{
            marginTop: '20px',
            paddingLeft: isMobile ? '12px' : '24px',
            paddingRight: isMobile ? '12px' : '24px',
          }}
        >
          {/* <Row gutter={24}> */}
          <AutoResponsive ref="container" {...getAutoResponsiveProps()}>
            {
              // arrayList.map(function (i) {
              //   return <div onClick={this.clickItemHandle} className="item" style={this.state.styleList[i]}>{i}</div>;
              // }, this)
              cards
            }
          </AutoResponsive>
          {/* </Row> */}
        </div>
        <Drawer
          title={i18n.t`Add card`}
          placement="right"
          closable={true}
          destroyOnClose
          onClose={() => {
            this.setState({
              drawablevisible: false,
            })
          }}
          visible={this.state.drawablevisible}
          // style={{ overflow: "hidden" }}
          width={640}
        >
          {allcards &&
            allcards.map(item => {
              const filter = {
                DailyReport: {
                  title: <Trans>Number of data reporting</Trans>,
                  img:
                    'http://lc-rohmehlw.cn-n1.lcfile.com/699d25c2e633fec68102/1555164312%281%29.jpg',
                },
                DailyApi: {
                  title: <Trans>Number of API calls</Trans>,
                  img:
                    'http://lc-rohmehlw.cn-n1.lcfile.com/3ca10d37b96ea84e9c18/1555164243%281%29.jpg',
                },
                Reports: {
                  title: <Trans>Number of Reporting in Project</Trans>,
                  img:
                    'http://lc-rohmehlw.cn-n1.lcfile.com/cdaf21afddecbc727563/1555164411%281%29.jpg',
                },
                EApis: {
                  title: <Trans>Call API details</Trans>,
                  img:
                    'http://lc-rohmehlw.cn-n1.lcfile.com/57aff9198fff07b69581/1555164481%281%29.jpg',
                },
                DeviceInfo: {
                  title: <Trans>Existing equipment</Trans>,
                  img:
                    'http://lc-rohmehlw.cn-n1.lcfile.com/2534d857a2496626e605/1555164518%281%29.jpg',
                },
                // UserState: {
                //   // title: <Trans>Existing equipment</Trans>,
                //   img: ""
                // }
              }
              let targ = filter[item]
              return (
                targ && (
                  <Card
                    title={targ.title}
                    hoverable
                    style={{ cursor: 'pointer' }}
                    onClick={e => {
                      onaddcard(item)
                    }}
                  >
                    <img src={targ.img} />
                  </Card>
                )
              )
            })}
        </Drawer>
      </div>
    )
  }
}

Dashboard.propTypes = {
  avatar: PropTypes.string,
  username: PropTypes.string,
  dashboard: PropTypes.object,
  loading: PropTypes.object,
}

export default Dashboard
